<template>
  <div class="station-map">
    <div id="container" class="map-wrap"></div>
    <div v-if="data.address" class="text">
      <div class="iconfont icon-station-map"></div>
      当前定位：{{ data.address }}（{{ data.lng }}/{{ data.lat }}）
    </div>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios';
import makerImg from '@/assets/images/station-icon.png';

const proxy: any = getCurrentInstance()?.proxy;

const data = reactive({
  key: import.meta.env.VITE_ENV_KEY,
  tempMarker: null as any,
  markerIcon: null as any,
  lng: proxy.$config.lng,
  lat: proxy.$config.lat,
  address: '',
});
let map: any, tMap: any, listener: any;

const emit = defineEmits(['set-location', 'set-region']);

const initMap = () => {
  tMap = (window as any).qq.maps; // TMap地图实例
  const center = new tMap.LatLng(data.lat, data.lng); //设置中心点坐标
  //初始化地图
  map = new tMap.Map('container', {
    center: center,
    zoom: 11, //缩放级别
  });

  data.tempMarker = new tMap.Marker({
    position: center,
    map: map,
  });
  data.tempMarker.setVisible(false);
  const size = new tMap.Size(30, 35);
  const scaleSize = new tMap.Size(30, 35);
  const origin = new tMap.Point(0, 0);
  const anchor = new tMap.Point(15, 35);
  const icon = new tMap.MarkerImage(makerImg, size, origin, anchor, scaleSize);
  data.tempMarker.setIcon(icon);

  listener = tMap.event.addListener(map, 'click', (e: any) => {
    console.log('eeee======', e);
    // 获取当前经纬度
    data.lng = e.latLng.lng;
    data.lat = e.latLng.lat;
    addMarker(data.lng, data.lat);
    emit('set-location', data.lng, data.lat);
  });
};

onMounted(() => {
  initMap();
});

onDeactivated(() => {
  tMap.event.removeListener(listener);
  map = null;
  tMap = null;
});

// 添加覆盖物
const addMarker = (lng: any, lat: any) => {
  data.lng = lng;
  data.lat = lat;
  map.panTo(new tMap.LatLng(lat, lng));
  data.tempMarker.setVisible(true);
  data.tempMarker.setPosition(new tMap.LatLng(lat, lng));
  parseLngLat();
};

//坐标获取地址
const parseLngLat = () => {
  axios
    .get(
      `/qqmap/ws/geocoder/v1/?location=${data.lat},${data.lng}&key=${data.key}`
    )
    .then((res: any) => {
      // data.address = res.data.result.address || '';
      const info = res.data.result.ad_info;
      if (info.adcode) {
        const obj = {
          code: info.adcode,
          name: `${info.province}${info.city}${info.district}`,
        };
        emit('set-region', obj);
      } else {
        emit('set-region', null);
      }
    });
};

// const getCityName = (code: any) => {
//   return new Promise((resolve) => {
//     axios
//       .get(`/qqmap/ws/district/v1/list?&key=${data.key}`)
//       .then((res: any) => {
//         data.address = res.data.result.address || '';
//         const info = res.data.result.ad_info;
//         if (info.adcode) {
//           const obj = {
//             code: info.adcode,
//             name: `${info.province}${info.city}${info.district}`,
//           };
//         } else {
//         }
//       });
//   });
// };

//地址获取坐标
const parseAddress = (address: string) => {
  return new Promise((resolve) => {
    const searchService = new tMap.SearchService({
      // location: city,
      pageIndex: 1,
      pageCapacity: 5,
      complete: (results: any) => {
        console.log('rr----', address, results);
        if (results.type === 'POI_LIST') {
          data.lng = results.detail.pois[0].latLng.lng;
          data.lat = results.detail.pois[0].latLng.lat;
          data.address = results.detail.pois[0].address;
          addMarker(data.lng, data.lat);
          resolve({ lng: data.lng, lat: data.lat });
        } else {
          ElMessage({
            message: '定位失败',
            type: 'warning',
          });
        }
      },
      error: () => {
        ElMessage({
          message: '定位失败',
          type: 'warning',
        });
      },
    });
    searchService.search(address);
  });
};

const setMarker = (lng: any, lat: any) => {
  data.lng = lng;
  data.lat = lat;
  map.panTo(new tMap.LatLng(lat, lng));
  data.tempMarker.setVisible(true);
  data.tempMarker.setPosition(new tMap.LatLng(lat, lng));
};

defineExpose({
  parseAddress,
  addMarker,
  setMarker,
});
</script>

<style lang="scss">
.station-map {
  .map-wrap {
    width: 660px;
    height: 400px;
  }
  .text {
    display: flex;
    margin-top: 6px;
    line-height: 15px;
    color: #555;
    font-size: 10px;

    .iconfont {
      margin-right: 5px;
      font-size: 16px;
      color: #b3c1f6;
    }
  }
}
</style>